package com.centaline.androidsalesblog.activities.mine;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomSheetBehavior;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.AppCompatTextView;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;

import com.centaline.androidsalesblog.R;
import com.centaline.androidsalesblog.adapter.FragmentTabLayoutAdapter;
import com.centaline.androidsalesblog.base.BaseActivity;
import com.centaline.androidsalesblog.constants.AppConstant;
import com.centaline.androidsalesblog.constants.ExtraConstant;
import com.centaline.androidsalesblog.fragments.calculate.EsfSaleCalcFragment;
import com.centaline.androidsalesblog.fragments.calculate.NewHouseCalcFragment;
import com.centaline.androidsalesblog.iml.TaxCalculateCallback;
import com.centaline.androidsalesblog.model.businissobject.TaxCalculateBo;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * 税费计算器
 * Created by Ruan on 2016/3/3.
 */
public class TaxCalcActivity extends BaseActivity implements View.OnClickListener {

    public static final double BUSINESS_TAX_RATE = 5.38;
    private TabLayout tl_calc;
    private ViewPager vp_loan_calc;
    private View overView;
    private BottomSheetBehavior bottomSheetBehavior;

    private LinearLayout ll_result;
    private AppCompatTextView atv_title1, atv_des1, atv_title2, atv_des2, atv_title3, atv_des3,
            atv_title4, atv_des4, atv_title5, atv_des5, atv_title6, atv_des6, atv_title7, atv_des7;

    private double business_tax;     //增值税（含附加税)
    private double ge_tax;     //个税

    private TaxCalculateCallback taxCalculateCallback = new TaxCalculateCallback() {
        @Override
        public void callBack(TaxCalculateBo taxCalculateBo) {
            calculateResult(taxCalculateBo);
        }
    };

    @Override
    protected int setLayoutId() {
        return R.layout.activity_tax_calc;
    }

    @Override
    protected void findViews() {
        setUniversalToolbar();
        tl_calc = (TabLayout) findViewById(R.id.tl_calc);
        vp_loan_calc = (ViewPager) findViewById(R.id.vp_loan_calc);
        overView = findViewById(R.id.overView);
        ll_result = (LinearLayout) findViewById(R.id.ll_result);
        atv_title1 = (AppCompatTextView) findViewById(R.id.atv_title1);
        atv_des1 = (AppCompatTextView) findViewById(R.id.atv_des1);
        atv_title2 = (AppCompatTextView) findViewById(R.id.atv_title2);
        atv_des2 = (AppCompatTextView) findViewById(R.id.atv_des2);
        atv_title3 = (AppCompatTextView) findViewById(R.id.atv_title3);
        atv_des3 = (AppCompatTextView) findViewById(R.id.atv_des3);
        atv_title4 = (AppCompatTextView) findViewById(R.id.atv_title4);
        atv_des4 = (AppCompatTextView) findViewById(R.id.atv_des4);
        atv_title5 = (AppCompatTextView) findViewById(R.id.atv_title5);
        atv_des5 = (AppCompatTextView) findViewById(R.id.atv_des5);
        atv_title6 = (AppCompatTextView) findViewById(R.id.atv_title6);
        atv_des6 = (AppCompatTextView) findViewById(R.id.atv_des6);
        atv_title7 = (AppCompatTextView) findViewById(R.id.atv_title7);
        atv_des7 = (AppCompatTextView) findViewById(R.id.atv_des7);

    }

    @Override
    protected void initViews() {

        bottomSheetBehavior = BottomSheetBehavior.from(ll_result);
        bottomSheetBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View bottomSheet, int newState) {
            }

            @Override
            public void onSlide(@NonNull View bottomSheet, float slideOffset) {
                overView.setAlpha(slideOffset);
                overView.setVisibility(slideOffset > 0 ? View.VISIBLE : View.GONE);
            }
        });

        List<String> mTitleList = new ArrayList<>();
        mTitleList.add("二手房");
        mTitleList.add("新房");

        List<Fragment> fragmentList = new ArrayList<>();
        EsfSaleCalcFragment esfSaleCalcFragment = new EsfSaleCalcFragment();
        esfSaleCalcFragment.setTaxCalculateCallback(taxCalculateCallback);
        NewHouseCalcFragment newHouseCalcFragment = new NewHouseCalcFragment();
        newHouseCalcFragment.setTaxCalculateCallback(taxCalculateCallback);
        fragmentList.add(esfSaleCalcFragment);
        fragmentList.add(newHouseCalcFragment);

        Bundle bundle = getIntent().getBundleExtra(ExtraConstant.TAX_BUNDLE);
        if (bundle != null) {
            esfSaleCalcFragment.setArguments(bundle);
        }

        tl_calc.setTabMode(TabLayout.MODE_FIXED);
        tl_calc.addTab(tl_calc.newTab().setText("二手房"));
        tl_calc.addTab(tl_calc.newTab().setText("新房"));

        FragmentTabLayoutAdapter fragmentCalcAdapter = new FragmentTabLayoutAdapter(getSupportFragmentManager(), fragmentList, mTitleList);
        vp_loan_calc.setAdapter(fragmentCalcAdapter);
        tl_calc.setupWithViewPager(vp_loan_calc);

    }

    /**
     * 计算结果
     */
    private void calculateResult(TaxCalculateBo taxCalculateBo) {

        double houseTotal;
        int modeType = taxCalculateBo.getModeType();
        int houseType = taxCalculateBo.getHouseType();  //1."普通住宅",2."非普通住宅"
        double houseArea = taxCalculateBo.getHouseArea();
        int buyYear = taxCalculateBo.getBuyYear();   // 房屋年限  0:"2年以内"  ; 1:"2-5年" ; 2:"5年以上"
        double houseUnitPrice = taxCalculateBo.getHouseUnitPrice();
        boolean buyerFirst = taxCalculateBo.isBuyerFirst();
        boolean sellerOnly = taxCalculateBo.isSellerOnly();
        int levyType = taxCalculateBo.getLevyType();   //征收类型  1,总价 2,差价
        double originPrice = taxCalculateBo.getOriginPrice() * 10000;    //原价
        switch (modeType) {
            //二手房
            case 1:
                double qi_tax;     //契税
                houseTotal = taxCalculateBo.getHouseTotal() * 10000;    //房屋总额
                //北上广深城市Code
                if (AppConstant.CityCode.equals("010") ||
                        AppConstant.CityCode.equals("021") ||
                        AppConstant.CityCode.equals("020") ||
                        AppConstant.CityCode.equals("0755")) {
                    //契税
                    if (buyerFirst) {
                        if (houseArea > 90) {
                            qi_tax = houseTotal * 1.5 / 100;
                        } else {
                            qi_tax = houseTotal / 100;
                        }
                    } else {
                        qi_tax = houseTotal * 3 / 100;
                    }
                    //增值税（含附加税)
                    if (!sellerOnly && levyType == 2 && buyYear == 1 && houseType == 2) {
                        business_tax = (houseTotal - originPrice) * BUSINESS_TAX_RATE / 100;
                    } else if (buyYear == 0 || (buyYear == 1 && houseType == 2) || (buyYear == 2 && houseType == 2 && !sellerOnly)) {
                        business_tax = houseTotal * BUSINESS_TAX_RATE / 100;
                    } else {
                        business_tax = 0;
                    }
                    //个税
                    if (buyYear == 2 && sellerOnly) {
                        ge_tax = 0;
                    } else if (houseTotal < originPrice && levyType == 2) {
                        ge_tax = 0;
                    } else {
                        if (levyType == 1) {
                            if (houseType == 1)
                                ge_tax = houseTotal / 100;
                            else
                                ge_tax = houseTotal * 2 / 100;
                        } else {
                            ge_tax = (houseTotal - originPrice) * 20 / 100;
                        }
                    }

                } else {    //非北上广深
                    //契税
                    if (buyerFirst && houseArea > 90) {
                        qi_tax = houseTotal * 1.5 / 100;
                    } else if (!buyerFirst && houseArea > 90) {
                        qi_tax = houseTotal * 2 / 100;
                    } else {
                        qi_tax = houseTotal / 100;
                    }
                    //增值税（含附加税)
                    if (buyYear == 0) {
                        business_tax = houseTotal * BUSINESS_TAX_RATE / 100;
                    } else {
                        business_tax = 0;
                    }
                    //个税
                    if (buyYear == 2 && sellerOnly) {
                        ge_tax = 0;
                    } else if (houseTotal < originPrice && levyType == 2) {
                        ge_tax = 0;
                    } else {
                        if (levyType == 1) {
                            ge_tax = houseTotal / 100;
                        } else {
                            ge_tax = (houseTotal - originPrice) * 20 / 100;
                        }
                    }
                }
                int qiiTax = doubleToInt(qi_tax);
                int businessTax = doubleToInt(business_tax);
                int geTax = doubleToInt(ge_tax);
                int total_tax = qiiTax + businessTax + 5 + geTax;

                atv_title1.setText("契税");
                atv_title2.setText("增值税（含附加税)");
                atv_title3.setText("印花税");
                atv_title4.setText("个人所得税");
                atv_title5.setText("总计");
                atv_title6.setText("");
                atv_title7.setText("");
                atv_des1.setText(String.format(Locale.CHINA, "%d元", qiiTax));
                atv_des2.setText(String.format(Locale.CHINA, "%d元", businessTax));
                atv_des3.setText("5元");
                atv_des4.setText(String.format(Locale.CHINA, "%d元", geTax));
                atv_des5.setText(String.format(Locale.CHINA, "%d元", total_tax));
                atv_des6.setText("");
                atv_des7.setText("");

                break;
            //新房
            case 2:
                double newQiTax;
                houseTotal = houseArea * houseUnitPrice;    //房屋总额
                //印花税
                double yh_tax = houseTotal * 5 / 10000;
                //契税
                if (houseArea <= 90) {
                    newQiTax = houseTotal / 100;
                } else if (houseArea > 144) {
                    newQiTax = houseTotal * 3 / 100;
                } else {
                    newQiTax = houseTotal * 1.5 / 100;
                }
                //公证费
                double gz_tax = newQiTax / 10;
                //委托办理产权手续费
                double wtbl_tax = houseTotal * 3 / 1000;
                //房屋买卖手续费
                double mm_tax;
                if (houseArea <= 120) {
                    mm_tax = 500;
                } else if (houseArea > 120 && houseArea < 5001) {
                    mm_tax = 1500;
                } else {
                    mm_tax = 5000;
                }
                int hTotal = doubleToInt(houseTotal);
                int yhTax = doubleToInt(yh_tax);
                int gzTax = doubleToInt(gz_tax);
                int qiTax = doubleToInt(newQiTax);
                int wtblTax = doubleToInt(wtbl_tax);
                int mmTax = doubleToInt(mm_tax);
                //合计
                int total = hTotal + yhTax + gzTax + qiTax + wtblTax + mmTax;

                atv_title1.setText("房屋总额");
                atv_title2.setText("印花税");
                atv_title3.setText("公证费");
                atv_title4.setText("契税");
                atv_title5.setText("委托办理产权手续费");
                atv_title6.setText("房屋买卖手续费");
                atv_title7.setText("合计");
                atv_des1.setText(String.format(Locale.CHINA, "%d元", hTotal));
                atv_des2.setText(String.format(Locale.CHINA, "%d元", yhTax));
                atv_des3.setText(String.format(Locale.CHINA, "%d元", gzTax));
                atv_des4.setText(String.format(Locale.CHINA, "%d元", qiTax));
                atv_des5.setText(String.format(Locale.CHINA, "%d元", wtblTax));
                atv_des6.setText(String.format(Locale.CHINA, "%d元", mmTax));
                atv_des7.setText(String.format(Locale.CHINA, "%d元", total));
                bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);

                break;

            default:
                break;
        }
        bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.overView:
                bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK &&
                bottomSheetBehavior.getState() == BottomSheetBehavior.STATE_EXPANDED) {
            bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 四舍五入取整
     */
    public int doubleToInt(Double d) {
        BigDecimal inter = new BigDecimal(d).setScale(0, BigDecimal.ROUND_HALF_UP);
        return inter.intValue();
    }
}
